<template>
  <div class="app-container">
    <div v-if="showSearch" class="search-container">
      <CommonSearch
        :formConfig="searchColumns"
        :inline="true"
        labelWidth="63"
        formItemWidth="auto"
        :model="searchParam"
      >
        <template #after>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="reset">
            <i-ep-refresh />
            重置
          </el-button>
        </template>
      </CommonSearch>
    </div>

    <el-card shadow="never" class="table-container">
      <!-- <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
          ><i-ep-delete />删除</el-button
        >
      </template> -->

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        @sort-change="onTableSortChanged"
      >
        <!-- 表格内容操作 -->
        <template v-for="item in tableColumns" :key="item">
          <TableColumn v-if="item.prop && item.isShow" :column="item">
            <template v-for="slot in Object.keys($slots)" #[slot]="scope">
              <slot :name="slot" v-bind="scope"></slot>
            </template>
          </TableColumn>
        </template>
        <el-table-column fixed="right" label="操作" width="200" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              ><i-ep-view />查看</el-button
            >
            <!-- <el-button
              type="primary"
              size="small"
              link
              @click="handleTableDelete(scope.row.id)"
              ><i-ep-delete />删除</el-button
            > -->
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <sysoperatelog
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="reset"
      @change-visible="changeVisible"
    />

    <!-- 列设置 -->
    <ColSetting
      v-model:col-setting="tableColumns"
      v-model:search-setting="searchColumns"
      @search-handle="(e:boolean) => (showSearch = e)"
    />
  </div>
</template>

<script setup lang="tsx">
import { useTable } from "@/utils/useTable";
import request from "@/utils/request";
import { filterOrder, handleSelectData } from "@/utils/commonHooks";

defineOptions({
  name: "SYSTEMSYSOPERATELOG",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/system/sysOperateLog/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({ sort: {} });

// 初始化搜索参数数据
const searchParamInit = {
  logLevel: "",
  applicationName: "",
  modular: "",
  responseCode: "",
  requestTimeSearch: [],
  requestTimeStart: "",
  requestTimeEnd: "",
  createdUserName: "",
};

const deleteParam = {
  api: "/system/sysoperatelog/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

//日志级别
const logLevelList: any = ref([]);
async function getLogLevelList() {
  const { data } = await request({
    url: `/system/dictionary/getSelectedItems/LogLevel`,
    method: "post",
  });
  logLevelList.value = data;
  handleSelectData("logLevel", logLevelList.value, searchColumns);
}

// 如果初始化表格需要排序=》const initParam = reactive({sort:''});
// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });
onMounted(() => {
  getTableList();
  getLogLevelList();
});

// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}

const addDialog = reactive<DialogOption>({
  visible: false,
  title: "",
  data: {},
});

// 查询详情
async function getSystemRole(id: string) {
  const { data } = await request({
    url: `/system/sysoperatelog/get/${id}`,
    method: "post",
  });
  addDialog.data = data;
}

/** 打开表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改";
    getSystemRole(roleObj.id);
  } else {
    addDialog.title = "新增";
  }
  addDialog.visible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getRequestTime(data: any) {
  if (data) {
    searchParam.value.requestTimeStart = data[0];
    searchParam.value.requestTimeEnd = data[1];
  } else {
    searchParam.value.requestTimeStart = "";
    searchParam.value.requestTimeEnd = "";
  }
}

/** 自定义设置方法   start **/

// 搜索参数 设置为响应式
const searchColumns: any = reactive([
  {
    type: "select",
    label: "日志级别",
    isShow: true,
    fieldName: "logLevel",
    placeholder: "请选择日志级别",
    initValue: null,
    defaultFirstOption: true,
    optionList: [],
  },
  {
    type: "date", // 普通输入框
    isShow: true,
    valueFormat: "YYYY-MM-DD",
    dataType: "daterange", // 类型, text/textarea
    label: "请求时间", // 标签文本
    fieldName: "requestTimeSearch", // 字段名称
    startPlaceholder: "开始日期", // 提示文字
    endPlaceholder: "结束日期", // 提示文字
    initValue: "", // 默认值
    rangeSeparator: "至",
    change: (e: any) => getRequestTime(e),
  },
  {
    type: "input", // 普通输入框
    isShow: true,
    inputType: "text", // 类型, text/textarea
    label: "模块", // 标签文本
    fieldName: "modular", // 字段名称
    placeholder: "请输入模块", // 提示文字
    initValue: "", // 默认值
  },
  {
    type: "input", // 普通输入框
    isShow: true,
    inputType: "text", // 类型, text/textarea
    label: "用户姓名", // 标签文本
    fieldName: "createdUserName", // 字段名称
    placeholder: "请输入用户姓名", // 提示文字
    initValue: "", // 默认值
  },
]);

// 接收 columns 并设置为响应式
const tableColumns = reactive([
  {
    prop: "logLevel",
    label: "日志级别",
    isShow: true,
    minWidth: 100,
    render: (scope: any) =>
      scope.row.logLevel === "ERROR" ? (
        <el-tag type="danger">{scope.row.logLevel}</el-tag>
      ) : (
        <el-tag>{scope.row.logLevel}</el-tag>
      ),
  },
  { prop: "applicationName", label: "应用", isShow: true },
  { prop: "modular", label: "模块", width: 160, isShow: true },
  {
    prop: "businessType",
    label: "功能",
    minWidth: 120,
    isShow: true,
  },
  {
    prop: "clientIp",
    label: "客户端 IP",
    minWidth: 100,
    isShow: true,
  },
  {
    prop: "executionTime",
    label: "耗时(毫秒)",
    minWidth: 100,
    isShow: true,
  },
  {
    prop: "responseCode",
    label: "响应结果",
    minWidth: 80,
    isShow: true,
  },
  {
    prop: "requestTime",
    label: "请求时间",
    minWidth: 150,
    isShow: true,
  },
  {
    prop: "createdUserName",
    label: "用户姓名",
    minWidth: 100,
    isShow: true,
  },
]);

// 是否显示搜索框
const showSearch = ref(true);

/** 列表项自定义方法   end **/
</script>
<style lang="scss" scoped>
:deep(.el-form .el-form-item__label) {
  width: 63px;
  justify-content: start !important;
  padding: 0 7px 0 0;
}
</style>
